package io.rong.imkit.webview

import android.text.TextUtils
import java.util.*

class RequestParams {
    private var params = LinkedHashMap<String, String>()

    fun set(params: LinkedHashMap<String, String>): RequestParams {
        this.params = params
        return this
    }

    operator fun get(key: String): String? {
        return params[key]
    }

    fun put(key: String, value: String): RequestParams {
        params[key] = value
        return this
    }

    fun build(): String? {
        var data: String? = null
        if (params.isNotEmpty()) {
            val sb = StringBuilder(data)
            for ((key, value) in params) {
                sb.append(key).append("=").append(value)
                sb.append("&")
            }
            sb.setLength(sb.length - 1)
            data = sb.toString()
        }
        return data
    }

    fun build(url: String): String? {
        var data = build()
        if (!TextUtils.isEmpty(data)) {
            if (!TextUtils.isEmpty(url)) {
                data = if (url.contains("?")) {
                    if (url.endsWith("?")) {
                        url + data
                    } else {
                        if (url.endsWith("&")) {
                            url + data
                        } else {
                            "$url&$data"
                        }
                    }
                } else {
                    "$url?$data"
                }
            }
        } else {
            data = url
        }
        return data
    }
}